import { RedoOutlined } from '@ant-design/icons'
import { truthy } from '@gnlab/utils'
import { Tag } from 'antd'
import c from 'classnames'
import type { ItemBaseProps } from '@/desktop/logics/contacts'
import services from '@/services'
import type { ExternalContact, TransferedExternal } from '@/services/contact-types'
import ContactItemContent from './content'
import s from './external.module.less'
import { Menu, menuItems } from './menu'

export default function ExternalItem(
  props: ItemBaseProps & {
    contact: ExternalContact | TransferedExternal
  },
) {
  const { contact, isTop, unread } = props

  const isTransfer = 'transfer' in contact
  const nameExtra = truthy(contact.deleted) ? <Tag styleName="deleted">删</Tag> : null
  const menu = useMemo(() => {
    return [
      menuItems.top(contact.id, isTop),
      menuItems.markUnread(contact.id, unread),
      // TODO: 原本自己发送出去的“转交客户”也要能刷新的，但现在没有刷新入口了
      {
        icon: <RedoOutlined />,
        title: '刷新资料',
        onClick: () => void services.externals.refreshInfo(contact.id),
      },
    ]
  }, [contact.id, isTop, unread])
  const side = isTransfer ? <TransferInfo contact={contact} /> : <Menu items={menu} />

  return <ContactItemContent
    {...props}
    nameExtra={nameExtra}
    side={side}
    className={{
      item: c(s.item, isTransfer && s.transfer),
      current: s.current,
      inner: s.inner,
      avatar: s.avatar,
    }}
  />
}

function TransferInfo(props: { contact: TransferedExternal }) {
  const { contact } = props

  function transferBack(e: React.MouseEvent<HTMLAnchorElement>) {
    e.stopPropagation()
    void services.transfers.makeBack(contact.id)
  }
  function transferReturn(e: React.MouseEvent<HTMLAnchorElement>) {
    e.stopPropagation()
    void services.transfers.makeReturn(contact.id)
  }

  return <div styleName="transfer-info">
    {contact.transfer.isGive ? (
      <div styleName="describe give">已转交给 {contact.transfer.toName}</div>
    ) : (
      <div styleName="describe receive">由 {contact.transfer.fromName} 转交</div>
    )}

    {contact.transfer.isGive ? (
      <a onClick={transferBack}>收回</a>
    ) : (
      <a onClick={transferReturn}>退回</a>
    )}
  </div>
}
